<script setup lang="ts">
import { ref } from 'vue'
import { get,post } from '@/utils/service'
import { VUE_APP_BASE_API } from '@/utils/baseConfig'
import { showConfirmDialog, showNotify } from 'vant'
const valCodeModel = ref({ load: true, butText: '获取验证码', sendStatus: 1, delay: 60 })
const member = ref({})
const memberCarInfoLength=ref(0)
const memberCarInfos = ref([])
const noEmpty = ref(false)
const showSignDialog = ref(false)
const active = ref('1')
const mobilePhone = ref()
const vinCode = ref()
const codeNum = ref()
const carPlate = ref()
const loadingStatus=ref(false);
function onClickLeft() {
  window.history.back()
}
queryCarMasterWechat()

function queryCarMasterWechat() {
  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  get('/memberWechatNew/queryCarMasterWechat', {})
    .then((res) => {
      if (res.code === 0) {
        member.value = res.data.member
        const temps = res.data.memberCarInfos
        if (temps == null || temps.length <= 0) {
          noEmpty.value = true
        } else {
          noEmpty.value = false
        }
        memberCarInfos.value = temps
        memberCarInfoLength.value=temps.length;
      } else {
        noEmpty.value = true
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
function bindCar() {
  showSignDialog.value = true
}
function phoneValidator() {
  const state = /^1\d{10}$/.test(mobilePhone.value)
  if (state) {
    valCodeModel.value.load = false
  } else {
    valCodeModel.value.load = true
  }
  return state
}
function codeValidator() {
  return /^[0-9]{4}$/.test(codeNum.value)
}
function vinCodeValidator(){//验证车架号
  const vinCod=vinCode.value;
  if(vinCod==''||vinCod.length!=17){
    return false;
  }
  return true;
}
function carPlateNoValidator(){
  const value=carPlate.value;
  const isEmp = value === "" || value === null || value === undefined;
  if(isEmp){
    return false;
  }
  const len = value.length;
  // 位数校验
  if (len !== 7 && len !== 8) return false;
  // 车牌号校验规则
  const PLATE_NO_PATTERN =/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[A-HJ-NP-Z]{1}(([A-HJ-NP-Z0-9]{5})|([0-9]{6}|[A-HJ-NP-Z]{1}[0-9]{5}|[0-9]{5}[A-HJ-NP-Z]{1}|[A-HJ-NP-Z]{2}[0-9]{4}))$/;
  if (PLATE_NO_PATTERN.test(value)) {
      // 新能源车
      if (len === 8) return true;
      // 7位时,后5位最多包含2位字母校验
      const arr = value.match(/[A-HJ-NP-Z]/g);
      if (arr.length <= 3) return true;
  }
  return false;
}
function sendMobileMessage() {
  valCodeModel.value.load = true
  valCodeModel.value.butText = '发送中...'
  let delay = valCodeModel.value.delay
  get('/memberWechatNew/sendMobileMessage', { mobilePhone: mobilePhone.value }).then((res) => {
    if (res.code === 0) {
      showNotify({ type: 'success', message: '验证码已发送，请注意查收', duration: 3000 })
      valCodeModel.value.sendStatus = 2
      delay--
      valCodeModel.value.butText = delay + 's后重新获取'
      //最后的innerHTML不能丢，否则delay为一个对象
      if (delay > 0) {
        const timeInt = setInterval(() => {
          valCodeModel.value.butText = delay + 's后重新获取'
          delay--
          if (delay <= 0) {
            clearInterval(timeInt)
            valCodeModel.value.load = false
            valCodeModel.value.sendStatus = 1
            valCodeModel.value.butText = '获取验证码'
            valCodeModel.value.delay = 60
          }
        }, 1000)
      }
    } else {
      showNotify({ type: 'danger', message: res.msg })
      valCodeModel.value.butText = '获取验证码'
    }
  })
}
function onClickTag(obj: object) {
  active.value = obj.name
}
function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function submitFrm(values: object) {
  loadingStatus.value = true // 显示加载状态
  values.authType=active.value;
  try {
    post('/memberWechatNew/saveBindCarWechat', values).then((res) => {
      if (res.code === 0) {
        showNotify({ type: 'success', message: res.msg , duration: 3000 })
        setTimeout(() => {
          window.location.reload();
        }, 1000)
      } else {
        showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
      }
    })
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function deleteBy(dbid:number,vinCode:string){
   showConfirmDialog({
    title: '解绑车主确认',
    message: '确定解绑'+vinCode+'车架号对应车主吗',
  })
    .then(() => {
      get('/memberWechatNew/saveDeleteBindCarWechat', { dbid:dbid}).then((res) => {
    if (res.code === 0) {
        showNotify({ type: 'success', message: res.msg , duration: 3000 })
        setTimeout(() => {
          window.location.reload();
        }, 1000)
    }else{
          showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
        }
      })
    })
    .catch(() => {
      // on cancel
    })

}
</script>
<template>
  <van-nav-bar title="车主信息" left-text="返回" left-arrow @click-left="onClickLeft" />
  <van-empty
    v-if="noEmpty == true"
    :image="VUE_APP_BASE_API+'/images/vue/noData.png'"
    image-size="100"
    description="还未绑定车主"
  />
  <div class="mainContent" v-if="noEmpty == true">
    <div style="width: 100%; padding: 12px">
      <van-button type="primary" style="width: 100%" @click="bindCar">绑定车辆</van-button>
    </div>
  </div>
  <div class="recommendCustomerContent" v-for="(memberCarInfo,index) in memberCarInfos" :key="memberCarInfo.dbid">
      <div class="recommendCustomerHeadr">
        <div class="recommendCustomerTitle">姓名：{{ memberCarInfo.name || 无 }}</div>
        <div class="recommendCustomerTitle">联系电话：{{ memberCarInfo.mobilePhone }}</div>
      </div>
      <div class="recommendCustomerInnerItem">
        <div class="recommendCustomerInnerItemContent">
          <van-cell-group
            style="
              --van-cell-line-height: 18px;
              --van-cell-label-font-size: 12px;
              --van-cell-vertical-padding: 6px;
              --van-cell-value-font-size: 12px;
            "
          >
            <van-cell title="车架号" :value="memberCarInfo.vinCode" />
            <van-cell
              title="购车时间"
              :value="memberCarInfo.successDate || '无'"
              ellipsis
              class="van-cell"
            />
            <van-cell
              title="销售顾问"
              :value="memberCarInfo.bussStaff || '无'"
              ellipsis
              class="van-cell"
            />
            <van-cell
              title="销售电话"
              :value="memberCarInfo.salerMobilePhone || '无'"
              ellipsis
              class="van-cell"
            />
          </van-cell-group>
        </div>
      </div>
      <div>
        <hr class="hrdashed" />
        <div class="recommendCustomerOper">
          <!--等等处理-->
          <div class="oprLeft" style="padding-left: 1px;">
            <van-button type="primary" class="buttCancel" @click="deleteBy(memberCarInfo.dbid,memberCarInfo.vinCode)" style="min-width: 150px;"
              >解绑</van-button
            >
          </div>
          <div class="oprRight" v-if="(index+1)==memberCarInfoLength" style="padding-right: 1px;">
            <van-button
              type="success"
              class="buttEdit"
               icon="plus"
              @click="bindCar" style="min-width: 150px;"
              >我有多辆车</van-button
            >
          </div>
        </div>
      </div>
    </div>
    <br />
  <van-popup
    closeable
    v-model:show="showSignDialog"
    position="bottom"
    round
    :style="{ height: '50%' }"
  >
    <div>
      <h3 style="text-align: center; line-height: 40px; height: 40px">车主认证</h3>
    </div>
      <div style="text-align: center; margin: auto 12px; padding: 12px">
        <van-tabs
          v-model:active="active"
          style="width: 100%"
          color="#c82030"
          title-active-color="#c82030"
          @click-tab="onClickTag"
          type="line"
          line-width="120px"
          border="true"
          sticky
        >
          <van-tab title="车架号认证" name="1">
            <van-form @failed="onFailed" @submit="submitFrm">
            <br></br>
            <van-cell-group inset>
              <van-field
                v-model="mobilePhone"
                label="联系电话"
                required="true"
                name="mobilePhone"
                placeholder="客户联系电话"
                type="tel"
                :rules="[
                  { required: true, message: '请填写手机号码' },
                  {
                    validator: phoneValidator,
                    message: '请输入正确的手机号格式',
                    trigger: 'onChange',
                  },
                ]"
              />
              <van-field
                required="true"
                v-model="codeNum"
                center
                clearable
                name="codeNum"
                type="number"
                label="短信验证码"
                placeholder="请输入短信验证码"
                :rules="[
                  { required: true, message: '请输入4位验证码' },
                  { validator: codeValidator, message: '请输入4位验证码', trigger: 'onChange' },
                ]"
              >
                <template #button>
                  <van-button
                    size="small"
                    type="primary"
                    :disabled="valCodeModel.load"
                    @click="sendMobileMessage"
                    >{{ valCodeModel.butText }}</van-button
                  >
                </template>
              </van-field>
              <van-field
                v-model="vinCode"
                label="车架号"
                required="true"
                name="vinCode"
                placeholder="车架号"
                type="tel"
                :rules="[{ required: true, message: '请填写车架号' }
                  ,{ validator: vinCodeValidator, message: '请输入17位车架号', trigger: 'onChange' },
                ]"
              />
            </van-cell-group>
               <br />
              <van-button
                round
                block
                type="primary"
                :loading="loadingStatus"
                loading-type="spinner"
                loading-text="提交中..."
                native-type="submit"
              >
                绑定车辆
              </van-button>
            </van-form>
          </van-tab>

          <van-tab title="车牌号认证" name="2">
            <br></br>
             <van-form @failed="onFailed" @submit="submitFrm">
            <van-cell-group inset>
              <van-field
                v-model="mobilePhone"
                label="联系电话"
                required="true"
                name="mobilePhone"
                placeholder="客户联系电话"
                type="tel"
                :rules="[
                  { required: true, message: '请填写手机号码' },
                  {
                    validator: phoneValidator,
                    message: '请输入正确的手机号格式',
                    trigger: 'onChange',
                  },
                ]"
              />
              <van-field
                required="true"
                v-model="codeNum"
                center
                clearable
                name="codeNum"
                type="number"
                label="短信验证码"
                placeholder="请输入短信验证码"
                :rules="[
                  { required: true, message: '请输入4位验证码' },
                  { validator: codeValidator, message: '请输入4位验证码', trigger: 'onChange' },
                ]"
              >
                <template #button>
                  <van-button
                    size="small"
                    type="primary"
                    :disabled="valCodeModel.load"
                    @click="sendMobileMessage"
                    >{{ valCodeModel.butText }}</van-button
                  >
                </template>
              </van-field>
              <van-field
                v-model="carPlate"
                label="车牌号"
                required="true"
                name="carPlate"
                placeholder="车牌号"
                type="tel"
                :rules="[{ required: true, message: '请填写车牌号' },
                 { validator: carPlateNoValidator, message: '请填写准确的车牌号', trigger: 'onChange' },
                ]"
              />
            </van-cell-group>
            <br />
              <van-button
                round
                block
                type="primary"
                :loading="loadingStatus"
                loading-type="spinner"
                loading-text="提交中..."
                native-type="submit"
              >
                绑定车辆
              </van-button>
          </van-form>
          </van-tab>
        </van-tabs>
      </div>
  </van-popup>
  <br />
</template>
